// 显示客服中心
function showCustomerService() {
    hideAccountCenter();
    $.post(FromUrl,{type:'customer_service',gid:gid},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
}

// 隐藏客服中心
function hideCustomerService() {
    const customerService = document.getElementById('customerService');
    if (customerService) {
        customerService.remove();
    }
}

// 显示公告列表
function showArticleList() {
    hideAccountCenter();
    $.post(FromUrl,{type:'article_list',gid:gid,cid:cid},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
}

// 隐藏公告列表
function hideArticleList() {
    const ArticleList = document.getElementById('ArticleList');
    if (ArticleList) {
        ArticleList.remove();
        showAccountCenter();
    }
}

// 显示公告详情
function showArticleDetail(id) {
    const ArticleList = document.getElementById('ArticleList');
    if (ArticleList) {
        ArticleList.remove();
    }
    $.post(FromUrl,{type:'article_detail',gid:gid,cid:cid,id:id},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
}

// 隐藏公告详情
function hideArticleDetail() {
    const ArticleList = document.getElementById('ArticleDetail');
    if (ArticleList) {
        ArticleList.remove();
        showArticleList();
    }
}

// 上一条或者下一条 type = 1 下一条 type = 2 上一条
function showArticle(id,type) {

    $.post(FromUrl,{type:'next_detail',gid:gid,cid:cid,id:id,next:type},function(html) {
        if(html.code==0){
            layer.msg(html.msg,{time:2000});
        }else {
            // 先清除原有内容
            const ArticleDetail = document.getElementById('ArticleDetail');
            if (ArticleDetail) {
                ArticleDetail.remove();
            }
            document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
        }
    });
}

// 问题提交表单
function showSubmitReport(reportType) {
    $.post(FromUrl,{type:'submit_report',gid:gid,reportType:reportType},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);

        layui.use(['upload', 'laydate', 'jquery'], function(){
            var upload = layui.upload;
            var laydate = layui.laydate;
            var $ = layui.jquery;

            $('.layui-textarea').on('input', function(){
                var val = $(this).val();
                $('.layui-word-aux').text(val.length+"/300");
            });

            // 日期时间选择器
            laydate.render({
                elem: '#time',
                type: 'datetime'
            });
            // 文件上传
            // 图片路径数组
            var imgPaths = [];
            upload.render({
                elem: '#uploadBtn',
                url: uploadImg,
                size: 4096, // 4M
                multiple: true,
                number: 5,
                accept: 'images',
                done: function(res){
                    console.log(res);
                    // 将返回的图片路径存入数组
                    imgPaths.push(res.url);
                    // 更新隐藏域的值
                    $('#images').val(imgPaths.join(','));
                    layer.msg('上传成功');
                },
                error: function(){
                    layer.msg('上传失败');
                }
            });
        });
    });
    hideCustomerService();

}

// 隐藏表单
function hideSubmitReport() {
    const submitReport = document.getElementById('submitReport');
    if (submitReport) {
        submitReport.remove();
    }
    showCustomerService();
}

//提交表单
function formReport(event){
    // 阻止默认行为
    if(event) event.preventDefault();
    // 基础表单数据
    var formData = $('#report_form').serializeArray();

    // 添加额外参数
    formData.push(
        {name: 'gid', value: gid},
        {name: 'uid', value: uid},
        {name: 'cid', value: cid}
    );

    // 转换为查询字符串
    var data = $.param(formData);
    $.post(submitReport,data,function(info){
        if(info.code==0) {
            layer.msg(info.msg,{time:2000});return false;
        }else if(info.code==1){
            layer.msg(info.msg,{time:2000});
            hideSubmitReport();
            return false;
        }else{
            // 其他错误
            layer.msg(info.msg || '提交失败，请重试', {time: 2000});return false;
        }
    })
    // 阻止表单默认提交
    return false;
}


// 显示进度查询
function showReportList() {
    $.post(FromUrl,{type:'report_list',gid:gid,uid:uid,token:token},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
    hideCustomerService();
}

// 隐藏进度查询
function hideReportList() {
    const customerService = document.getElementById('ReportList');
    if (customerService) {
        customerService.remove();
    }
    showCustomerService();
}

function showReportDetail(id) {
    $.post(FromUrl,{type:'report_detail',gid:gid,uid:uid,id:id},function(html) {
        document.getElementById('floatBall').insertAdjacentHTML('afterend', html);
    });
    const customerService = document.getElementById('customerService');
    if (customerService) {
        customerService.remove();
    }
    const ReportList = document.getElementById('ReportList');
    if (ReportList) {
        ReportList.remove();
    }
}
function hideReportDetail() {
    const reportDetail = document.getElementById('ReportDetail');
    if (reportDetail) {
        reportDetail.remove();
    }
    showReportList();
}

function sendMessage() {
    const message  = document.getElementById('userInput').value;
    const imagePreview = document.getElementById('imagePreview');
    const selectedImage = document.getElementById('imagePreview').src;
    const previewContainer = document.getElementById('previewContainer');
    const imageInput = document.getElementById('imageInput');


    if (message || selectedImage) {
        if (message) {
            addUserMessage(message, 'text');
        }

        if (selectedImage) {
            addUserMessage(selectedImage, 'image');
            imagePreview.removeAttribute('src');
            previewContainer.classList.remove('visible');
            imageInput.value = '';
        }
        userInput.value = '';

        setTimeout(() => {
            hideTypingIndicator();
        }, 1000 + Math.random() * 1000);
        // 添加到后台
    }
}

function addUserMessage(content, type = 'text') {
    const messageDiv = document.createElement('div');
    const chatContainer = document.getElementById('chatContainer');
    messageDiv.className = 'message user-message';
    //同步消息
    sendMsg(content,type);
    if (type === 'text') {
        messageDiv.textContent = content;
    } else if (type === 'image') {
        const img = document.createElement('img');
        img.src = content;
        img.className = 'image-message';
        messageDiv.appendChild(img);
        chatContainer.removeAttribute('style');
    }

    const timeDiv = document.createElement('div');
    timeDiv.className = 'user-time';
    timeDiv.textContent = getCurrentTime();

    messageDiv.appendChild(timeDiv);
    chatContainer.appendChild(messageDiv);
    scrollToBottom(chatContainer);

}

//同步到后台 sendPlayerMsg
function sendMsg(content,type){
    const customer_id = document.getElementById('customer_id').value;
    const data = {
        uid:uid,
        gid:gid,
        cid:cid,
        content:content,
        type:type,
        customer_id:customer_id,
    };
    $.post(sendPlayerMsg,data,function(info) {
        if(info.code==1) {
            msg_id = info.data;
            return info.data;
        }
    });
}

function scrollToBottom(chatContainer) {
    // 直接滚动到底部（不手动补偿）
    chatContainer.scrollTop = chatContainer.scrollHeight;
    const chat = document.getElementById('chatContainer');
    chat.scrollTop = chat.scrollHeight + 86;
    console.log(chat.scrollTop); // 若值未改变，说明滚动被阻止
    // 调试日志
    console.log(
        '修正后滚动参数:',
        `内容高度=${chatContainer.scrollHeight}`,
        `窗口高度=${chatContainer.clientHeight}`,
        `滚动位置=${chatContainer.scrollTop}`
    );
}
function getCurrentTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
}

function hideTypingIndicator() {
    const typingIndicator = document.getElementById('typingIndicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
}

// 图片选择事件
function imagePreview(e) {
    const imagePreview = document.getElementById('imagePreview');
    const previewContainer = document.getElementById('previewContainer');
    const chatContainer = document.getElementById('chatContainer');
    if (e.files && e.files[0]) {
        const file = e.files[0];
        if (file.type.match('image.*')) {
            const reader = new FileReader();

            reader.onload = function(event) {
                imagePreview.src = event.target.result;
                previewContainer.classList.add('visible');
                chatContainer.style.maxHeight = '44vh';

                scrollToBottom(chatContainer);
                // selectedImage = event.target.result;
            };

            reader.readAsDataURL(file);
        }
    }
}
// 点击放大图片
function openModal(img) {
    layer.open({
        type: 1,
        title: false,
        closeBtn: 1,
        area: ['95%', 'auto'],
        skin: 'layui-layer-nobg',
        shadeClose: true,
        content: '<img src="' + img.src + '" style="max-width: 95%;">'
    });
}
// 取消预览
function cancelPreview() {
    const imagePreview = document.getElementById('imagePreview');
    const previewContainer = document.getElementById('previewContainer');
    const imageInput = document.getElementById('imageInput');

    imagePreview.removeAttribute('src');
    previewContainer.classList.remove('visible');
    imageInput.value = '';
    document.getElementById('chatContainer').removeAttribute('style');
}